home *** CD-ROM | disk | FTP | other *** search
- Path: news2.ios.com!usenet
- From: vlad@gramercy.ios.com (Vlastimil Adamovsky)
- Newsgroups: comp.lang.c++
- Subject: Re: Pointers to member functions HOW?
- Date: Fri, 26 Jan 1996 05:13:34 GMT
- Organization: Internet Online Services
- Message-ID: <4e9nh8$iji@news2.ios.com>
- References: <31067074.6B53@compuserve.com>
- NNTP-Posting-Host: ppp-47.ts-7.hck.idt.net
- X-Newsreader: Forte Free Agent 1.0.82
-
- Roberto Ortiz <74011.3205@compuserve.com> wrote:
-
- >I've been attempting for some time now to declare a pointer to a class'
- >memeber function. I have no problem with pointers to regular functions, but
- >with class members, I run into one of two problems:
-
- >a) I can't assign the function to the pointer.
- >b) I can't call the pointer as a function.
-
- >whenever I solve one, I get the other.
-
- >Here's some example code in Borland C++:
-
- >#include <stdio.h>
-
- >void RegularFunction(int iVal)
- >{
- > printf("[%d]\n", iVal);
- >};
-
- >class TTest {
- >public:
- > void MemberFunction(int iVal)
- > {
- > printf("[%d]\n", iVal);
- > };
- >};
-
- >void main()
- >{
- > typedef void (TFuncVoidInt)(int);
-
- > TFuncVoidInt *Func0;
- > TFuncVoidInt *Func1;
-
- > void (TTest::*Func2)(int);
-
- > Func0 = RegularFunction;
- > Func1 = TTest::MemberFunction;
- > Func2 = &TTest::MemberFunction;
-
- > Func0(100);
- > Func1(100);
- > Func2(100);
- >};
-
- >with this code, I get the following compiler messages:
-
- >Compiling PTEST.CPP:
- >Error PTEST.CPP 26: Cannot convert 'void (TTest::*)(int)' to 'void (*)(int)'
- >in function main()
- >Error PTEST.CPP 31: Call of nonfunction in function main()
- >function main()
-
- The compiling error messages are very correct:
-
- 1) you cannot cast member function to non-member. It is nonsense
-
- 2)
- ....
- ....
- > Func0(100);
- > Func1(100);
- > Func2(100);
- You declared Func2 as a pointer to a member function. A member
- function mus be called together with the with the instance that
- contains this member function.
- In you case you should do the following:
-
- TTest * p;
- // we assume that the p has been initialized somehow....
- .....
- (p->*Func2) (100);
-
- >};
-
-
- *******************************************
- * Vlastimil Adamovsky *
- * Smalltalk, C++ and Envelop development *
- *******************************************
-
-